<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>给开源项目提了个PR | 后端学习记录</title><meta name="keywords" content="Java"><meta name="author" content="h0ss"><meta name="copyright" content="h0ss"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="拖了很久的文章终于动笔了，两个月前提的PR现在才开始写总结文章，lazydog一只…. 1、背景首先介绍下 Sa-Token ，这是一个轻量级 Java 权限认证框架，主要解决：登录认证、权限认证、单点登录、OAuth2.0、分布式Session会话、微服务网关鉴权 等一系列权限相关问题。  优化源自其中的一个随机数获取逻辑实现，具体 PR 如图所示，该PR已被合并到主线代码中，在10月28日发布">
<meta property="og:type" content="article">
<meta property="og:title" content="给开源项目提了个PR">
<meta property="og:url" content="https://blog.gpnusz.cn/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/index.html">
<meta property="og:site_name" content="后端学习记录">
<meta property="og:description" content="拖了很久的文章终于动笔了，两个月前提的PR现在才开始写总结文章，lazydog一只…. 1、背景首先介绍下 Sa-Token ，这是一个轻量级 Java 权限认证框架，主要解决：登录认证、权限认证、单点登录、OAuth2.0、分布式Session会话、微服务网关鉴权 等一系列权限相关问题。  优化源自其中的一个随机数获取逻辑实现，具体 PR 如图所示，该PR已被合并到主线代码中，在10月28日发布">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog.gpnusz.cn/img/avatar.jpg">
<meta property="article:published_time" content="2022-11-15T17:28:40.000Z">
<meta property="article:modified_time" content="2022-11-15T17:31:06.530Z">
<meta property="article:author" content="h0ss">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog.gpnusz.cn/img/avatar.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://blog.gpnusz.cn/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2022-11-16 01:31:06'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">后端学习记录</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">给开源项目提了个PR</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-11-15T17:28:40.000Z" title="发表于 2022-11-16 01:28:40">2022-11-16</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-11-15T17:31:06.530Z" title="更新于 2022-11-16 01:31:06">2022-11-16</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span></div></div></div><article class="post-content" id="article-container"><p>拖了很久的文章终于动笔了，两个月前提的PR现在才开始写总结文章，lazydog一只….</p>
<h3 id="1、背景"><a href="#1、背景" class="headerlink" title="1、背景"></a>1、背景</h3><p>首先介绍下 <a target="_blank" rel="noopener" href="https://gitee.com/dromara/sa-token">Sa-Token</a> ，这是一个轻量级 Java 权限认证框架，主要解决：登录认证、权限认证、单点登录、OAuth2.0、分布式Session会话、微服务网关鉴权 等一系列权限相关问题。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/cbed03f799f843489c6d8dba08281706~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>优化源自其中的一个随机数获取逻辑实现，具体 <a target="_blank" rel="noopener" href="https://gitee.com/dromara/sa-token/pulls/180">PR</a> 如图所示，该PR已被合并到主线代码中，在10月28日发布的 v1.32.0 中已经完成替换。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/78e3bd916b304388bc1900a19280e6f9~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>主要工作就是使用 ThreadLocalRadom 获取随机数去替换原来的 Random 获取，PR中也有给出具体的测试样例和数据来佐证更换之后的性能提升，但今天这篇文章还是想更全面地讲一下几种随机数获取逻辑的使用和性能差异。</p>
<h3 id="2、随机数获取方式"><a href="#2、随机数获取方式" class="headerlink" title="2、随机数获取方式"></a>2、随机数获取方式</h3><h4 id="1）多例Random"><a href="#1）多例Random" class="headerlink" title="1）多例Random"></a>1）多例Random</h4><p>在 Java 中我们获取随机数自然而然会想到使用 Random 对象的 nextXX 方法去获取，这也是最简单的一种，例如可以这样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaUtils1</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getRandomString</span><span class="params">(<span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">        String str = <span class="string">&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;</span>;</span><br><span class="line">        Random random = <span class="keyword">new</span> Random();</span><br><span class="line">        StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; length; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> number = random.nextInt(<span class="number">62</span>);</span><br><span class="line">            sb.append(str.charAt(number));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这种方式获取确实很简单，但还是存在一个可优化的点，我们可以发现这是一个静态方法获取随机数，每次进入到这个方法都会创建一个新的 Random 对象。虽然说方法结束后内存会被回收，但在访问量大的情况下，反复创建对象的开销也不能忽视，因此有了第二种方式获取随机数。</p>
<h4 id="2）单例Random"><a href="#2）单例Random" class="headerlink" title="2）单例Random"></a>2）单例Random</h4><p>单例获取实际上就是将 Random 对象升级为类成员，这样可以避免重复创建对象，例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaUtils2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Random random = <span class="keyword">new</span> Random();</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getRandomString</span><span class="params">(<span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">        String str = <span class="string">&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;</span>;</span><br><span class="line">        StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; length; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> number = random.nextInt(<span class="number">62</span>);</span><br><span class="line">            sb.append(str.charAt(number));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>显而易见地，在升级为类成员之后 Random 对象只需创建一次，在创建开销上明显是占优的，但具体的性能分析还要等待真正的测试。</p>
<h4 id="3）单例ThreadLocalRandom"><a href="#3）单例ThreadLocalRandom" class="headerlink" title="3）单例ThreadLocalRandom"></a>3）单例ThreadLocalRandom</h4><p><strong>ThreadLocalRandom</strong> 是 JDK7 提供并发产生随机数的工具类，能够解决多线程下的争用问题，在使用上和Random略有不同：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaUtils3</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocalRandom random = ThreadLocalRandom.current();</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getRandomString</span><span class="params">(<span class="keyword">int</span> length)</span> </span>&#123;</span><br><span class="line">        String str = <span class="string">&quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;</span>;</span><br><span class="line">        StringBuffer sb = <span class="keyword">new</span> StringBuffer();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; length; i++) &#123;</span><br><span class="line">            <span class="keyword">int</span> number = random.nextInt(<span class="number">62</span>);</span><br><span class="line">            sb.append(str.charAt(number));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> sb.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到这里首先是用 ThreadLocalRandom 的静态方法 current 来获取到一个实例，接着再去调用 nextXX 方法实现随机数获取。</p>
<h3 id="3、线程争用分析"><a href="#3、线程争用分析" class="headerlink" title="3、线程争用分析"></a>3、线程争用分析</h3><h4 id="1）Random-的线程争用问题"><a href="#1）Random-的线程争用问题" class="headerlink" title="1）Random 的线程争用问题"></a>1）Random 的线程争用问题</h4><p>实际上我们使用单例 Random 对象在单线程下是没问题的，但在多线程下虽不会有线程安全问题但会发生线程争用，进而影响生成效率，那么线程争用主要体现在哪呢？</p>
<p>以 nextInt 为例，贴代码分析下：</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3fcf9d355bcf48338172f090563c68b9~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>可以看到里面调用了 next 方法，进而在 next 方法中是取旧的 seed 去做位运算，进而得到新的 seed 并计算出随机数，这里我们只需要知道这个过程就行了，位运算的具体操作不是本文重点。</p>
<p>这里我们也可以发现这个 seed 是 AtomicLong 类型的，意味着其可以保证原子操作，也就避免了线程安全问题的出现。同时，意味着在高并发场景下会有较多的 CAS 失败操作，不断自旋重试，进而造成 CPU 处理效率降低且吞吐量下降。</p>
<h4 id="2）ThreadLocalRandom-的解决方案"><a href="#2）ThreadLocalRandom-的解决方案" class="headerlink" title="2）ThreadLocalRandom 的解决方案"></a>2）ThreadLocalRandom 的解决方案</h4><p>接下来我们看看 ThreadLocalRandom 在源码层面有什么区别。</p>
<p>首先进入 current 方法，可以发现这里是调用了 UNSAFE 来保证单例，如果还没有创建过就进入到初始化方法，我们跟进去看看。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/32f20d35490f4d23949de65d640817e6~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>这里需要说明的是，PROBE 实际上是一个状态变量，如果为0说明还没初始化，如果为1说明已经初始化完成，而 SEED 很明显就是种子变量了，这两个变量都是通过UNSAFE中的方法给设置到线程中去，那么我们去 Thread 中找一下。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5b261aa6716f4e48be7825247c538e0f~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>可以发现这两个变量在 Thread 类中是有体现的，也就是说实际上种子是存储在 Thread 中的，与线程强相关的。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/2b472d4a4e124d54a10c3ec1547fdea0~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>从这里我们可以发现在单例下种子实际上是通过存储在 Thread 中来实现线程隔离的。</p>
<p>接下来看看 nextInt 方法，可以发现这里除了生成随机数，还对 seed 进行更新，同样是使用 UNSAFE 去更新种子。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/05facbd904e64ed7a54b2a32472790a0~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>其他更细节的操作就不分析了，到这里我们可以得出结论：ThreadLocalRandom 减少线程争用的操作就是将 seed 与线程绑定起来，每个线程有自己的 seed 这样即使在多线程环境下，seed 的更新也不会造成频繁 CAS 导致吞吐量降低。</p>
<h3 id="4、性能分析"><a href="#4、性能分析" class="headerlink" title="4、性能分析"></a>4、性能分析</h3><p>在分析了源码层面的区别之后，还应该从实际的使用出发，测试下性能的表现。</p>
<h4 id="1）单线程测试"><a href="#1）单线程测试" class="headerlink" title="1）单线程测试"></a>1）单线程测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RandomTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> times = <span class="number">100000</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        singleThread();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">singleThread</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            SaUtils.getRandomString(<span class="number">64</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;single thread-cost time : &quot;</span> + (end - start) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start1 = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            SaUtils2.getRandomString(<span class="number">64</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">long</span> end1 = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;single thread-cost time : &quot;</span> + (end1 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> start2 = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            SaUtils3.getRandomString(<span class="number">64</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">long</span> end2 = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;single thread-cost time : &quot;</span> + (end2 - start2) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里简单地做一个单线程的测试，其中涉及到的生成随机数的类都在上面第二点中有列出，这里不再重复。</p>
<p>这里做了10w次的获取操作，打印出耗时具体如下，可能稍有误差，不过大致可以体现出差异。</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7495d43706d54309beaf7d4e2e00969f~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>可以发现多例 Random 确实有一些性能损耗，而单例 ThreadLocalRandom 的耗时是最短的。</p>
<h4 id="2）多线程测试"><a href="#2）多线程测试" class="headerlink" title="2）多线程测试"></a>2）多线程测试</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RandomTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> times = <span class="number">100000</span>;</span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">int</span> threadNum = <span class="number">10</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        poolThread();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">poolThread</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        ExecutorService pool = Executors.newFixedThreadPool(threadNum);</span><br><span class="line">        CountDownLatch cdl = <span class="keyword">new</span> CountDownLatch(times);</span><br><span class="line">        <span class="keyword">long</span> start1 = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            pool.execute(() -&gt; &#123;</span><br><span class="line">                SaUtils.getRandomString(<span class="number">64</span>);</span><br><span class="line">                cdl.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        cdl.await();</span><br><span class="line">        <span class="keyword">long</span> end1 = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;cost time : &quot;</span> + (end1 - start1) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line">        pool.shutdown();</span><br><span class="line"></span><br><span class="line">        pool = Executors.newFixedThreadPool(threadNum);</span><br><span class="line">        CountDownLatch cdl2 = <span class="keyword">new</span> CountDownLatch(times);</span><br><span class="line">        <span class="keyword">long</span> start2 = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            pool.execute(() -&gt; &#123;</span><br><span class="line">                SaUtils2.getRandomString(<span class="number">64</span>);</span><br><span class="line">                cdl2.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        cdl2.await();</span><br><span class="line">        <span class="keyword">long</span> end2 = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;cost time : &quot;</span> + (end2 - start2) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line">        pool.shutdown();</span><br><span class="line"></span><br><span class="line">        pool = Executors.newFixedThreadPool(threadNum);</span><br><span class="line">        CountDownLatch cdl3 = <span class="keyword">new</span> CountDownLatch(times);</span><br><span class="line">        <span class="keyword">long</span> start3 = System.currentTimeMillis();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; times; i++) &#123;</span><br><span class="line">            pool.execute(() -&gt; &#123;</span><br><span class="line">                SaUtils3.getRandomString(<span class="number">64</span>);</span><br><span class="line">                cdl3.countDown();</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        cdl3.await();</span><br><span class="line">        <span class="keyword">long</span> end3 = System.currentTimeMillis();</span><br><span class="line">        System.out.println(<span class="string">&quot;cost time : &quot;</span> + (end3 - start3) + <span class="string">&quot;ms&quot;</span>);</span><br><span class="line">        pool.shutdown();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里测试了10个线程同时获取的情况，同样是获取10w次，具体的数据如下：</p>
<p><img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/fef96563efb0435191b39a85201b36c1~tplv-k3u1fbpfcp-zoom-1.image"></p>
<p>从结果可以看出，在多线程环境下，由于存在线程争用，单例的 Random 表现最不理想，耗时几乎是多例 Random 的四倍，这也印证了我们前面的分析。</p>
<p>相比之下，单例 ThreadLocalRandom 表现依旧是最佳的，耗时上大概是多例 Random 的 40%，由于机器差异可能数据有所不同，不过大致上是这个量级。</p>
<h3 id="5、总结"><a href="#5、总结" class="headerlink" title="5、总结"></a>5、总结</h3><p>基于上面的理论分析和性能分析，我们可以发现不管是单线程还是多线程环境下，ThreadLocalRandom 的表现都是比较占优的，特别是在高并发的情况下，使用这种随机数获取方式可以带来一定的性能提升。</p>
<p>回到PR本身，Sa-Token 是一个认证鉴权框架，其 token 的生成默认基于随机数生成，同时 token 的获取会贯穿整个认证鉴权过程，那么随机数的获取效率在这里就显得至关重要了，也是基于框架的特点，才提出了这个修改建议，同时也很高兴这个修改建议在经过官方团队审核之后得以采纳。</p>
<p>其实回看整个分析过程，并没有涉及到很高深的技术点，这也启发自己积极去探索更多的应用场景，找到更合适的解决方案，为开源社区贡献自己微不足道的力量。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">h0ss</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://blog.gpnusz.cn/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/">https://blog.gpnusz.cn/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://blog.gpnusz.cn" target="_blank">后端学习记录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java/">Java</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/2022/09/03/%E3%80%90MySQL%E3%80%91InnoDB%E7%9A%84%E8%A1%8C%E6%A0%BC%E5%BC%8F/"><img class="next-cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【MySQL】InnoDB的行格式</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/08/21/【Debug】bitField-引发的栈溢出排错记/" title="【Debug】bitField 引发的栈溢出排错记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-21</div><div class="title">【Debug】bitField 引发的栈溢出排错记</div></div></a></div><div><a href="/2022/07/16/【RPC】详解SPI机制/" title="【RPC】详解SPI机制"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-16</div><div class="title">【RPC】详解SPI机制</div></div></a></div><div><a href="/2022/07/10/【RPC】基本网络通信模型/" title="【RPC】基本网络通信模型"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-10</div><div class="title">【RPC】基本网络通信模型</div></div></a></div><div><a href="/2022/07/02/【JVM】类加载全过程简记/" title="【JVM】类加载全过程简记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-07-02</div><div class="title">【JVM】类加载全过程简记</div></div></a></div><div><a href="/2022/06/28/【RPC】RPC实战与核心的学习笔记/" title="【RPC】RPC实战与核心的学习笔记"><img class="cover" src="https://i.loli.net/2021/09/01/PvqRnTrUBh1a37J.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-06-28</div><div class="title">【RPC】RPC实战与核心的学习笔记</div></div></a></div><div><a href="/2022/05/09/【Debug】Dubbo异常处理排错记/" title="【Debug】Dubbo异常处理排错记"><img class="cover" src="https://i.loli.net/2021/09/01/PRTlcsGZMQ7yBqn.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-05-09</div><div class="title">【Debug】Dubbo异常处理排错记</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="/img/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">h0ss</div><div class="author-info__description">一个苦逼后端仔的学习记录</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">51</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">14</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/h0ss"><i class="fab fa-github"></i><span>Gitee仓库</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">Java后端技术栈语雀文档：https://www.yuque.com/oliver-wdtb1/java</div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/11/16/%E7%BB%99%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%E6%8F%90%E4%BA%86%E4%B8%AAPR/" title="给开源项目提了个PR">给开源项目提了个PR</a><time datetime="2022-11-15T17:28:40.000Z" title="发表于 2022-11-16 01:28:40">2022-11-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/09/03/%E3%80%90MySQL%E3%80%91InnoDB%E7%9A%84%E8%A1%8C%E6%A0%BC%E5%BC%8F/" title="【MySQL】InnoDB的行格式">【MySQL】InnoDB的行格式</a><time datetime="2022-09-02T18:17:38.000Z" title="发表于 2022-09-03 02:17:38">2022-09-03</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/08/21/%E3%80%90Debug%E3%80%91bitField-%E5%BC%95%E5%8F%91%E7%9A%84%E6%A0%88%E6%BA%A2%E5%87%BA%E6%8E%92%E9%94%99%E8%AE%B0/" title="【Debug】bitField 引发的栈溢出排错记">【Debug】bitField 引发的栈溢出排错记</a><time datetime="2022-08-20T18:10:40.000Z" title="发表于 2022-08-21 02:10:40">2022-08-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/16/%E3%80%90RPC%E3%80%91%E8%AF%A6%E8%A7%A3SPI%E6%9C%BA%E5%88%B6/" title="【RPC】详解SPI机制">【RPC】详解SPI机制</a><time datetime="2022-07-15T18:51:57.000Z" title="发表于 2022-07-16 02:51:57">2022-07-16</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2022/07/14/%E3%80%90Redis%E3%80%91%E9%87%8D%E8%A6%81%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%9F%BA%E7%A1%80/" title="【Redis】重要数据结构基础">【Redis】重要数据结构基础</a><time datetime="2022-07-13T17:22:08.000Z" title="发表于 2022-07-14 01:22:08">2022-07-14</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-show-text.min.js" data-mobile="false" data-text="爱国,敬业,诚信,友善,自由,平等,公正,法治,富强,民主,文明,和谐" data-fontsize="16px" data-random="false" async="async"></script></div></body></html>